package com.xjscrm.common.spring.exception;


import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.result.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author jianghan
 * @date 2017/1/10
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 非法参数验证异常
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(value = HttpStatus.OK)
    public ResponseResult handleMethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        String errmsg = "参数错误";
        if (fieldErrors!=null && fieldErrors.size()>0){
            errmsg = fieldErrors.get(0).getDefaultMessage();
        }
        logger.error("handleMethodArgumentNotValidException");
        return new ResponseResult(ResponseCode.PARAMETER_EXCEPTION,"参数异常",errmsg);
    }

    /**
     * 业务层异常处理
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseResult businessExceptionHandler(HttpServletRequest request, BusinessException exception) {
        StackTraceElement[] stackTraceElements = exception.getStackTrace();
        logger.error("businessException:{}",exception.getMessage()+"::"+stackTraceElements[0].toString());
        Integer code = exception.getCode();
        code = (code==null? ResponseCode.BUSINESS_EXCEPTION:code);
        return new ResponseResult(code,exception.getMessage());
    }

    /**
     * 默认的异常处理
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseResult exceptionHandler(HttpServletRequest request, Exception exception) {
        logger.error("exception:",exception);
        return new ResponseResult(ResponseCode.ERROR,"系统异常!");
    }
}
